const express = require("express");
const cors = require("cors");
const db = require("./libs/DBHelper");
const file = require("./libs/fileHelper");
const md5 = require("md5");
const { request, response, json } = require("express");


let server = express();
//配置静态资源
server.use(express.static("./../src"));


//配置中间件
//post能够快速使用 body
server.use(express.urlencoded({ extended: false }));
server.use(express.json());

server.use(cors()); //配置跨域

// 登录
server.post("/account/login", async(request, response) => {
    //1.接受前端的数据 (用户名和密码)
    let { user, pwd } = request.body;
    //2. 准备sql语句
    let sql = "SELECT `uId`,`uName`,`uSex`,`uPhone` FROM `userinfo` WHERE uname=? AND upwd=? AND ustatus=1;";
    let parmas = [
        user,
        md5(md5(pwd) + "cs2104")
    ]
    console.log(parmas);
    try {
        let result = await db.exec(sql, parmas);
        if (result && result.length >= 1) {
            response.json({
                msg: "登录成功!",
                data: result,
                code: 200
            })
        } else {
            response.json({
                msg: "登录失败!",
                code: 200
            })
        }

    } catch (error) {
        response.json({
            msg: "登录失败!",
            err: error,
            code: -200
        })
    }
})

// 注册
server.post("/account/reg", async function(request, response) {
    //1.接受参数 
    let { user, pwd, sex, phone } = request.body;
    //2.准备sql语句
    let sql = "INSERT INTO `userinfo` (`uName`,`uPwd`,`uSex`,`uPhone`)VALUES(?,?,?,?);";
    //参数
    let parmas = [user, md5(md5(pwd) + "cs2104"), sex, phone];

    try {
        let result = await db.exec(sql, parmas);
        //注意:除了查询返回的是数组,
        //其他 (插入,修改,删除)返回的 受影响行数
        //不是undefined并且受影响行数大于等于1
        console.log(result);
        let isReg = result && result.affectedRows;
        response.json({
            msg: isReg ? "注册成功!" : '注册失败!',
            code: 200
        })
    } catch (error) {
        response.json({
            msg: '注册失败!',
            err: error,
            code: -200
        })
    }
})

// 获取所有的产品信息
server.get("/api/prodList", async(request, response) => {

    var data = JSON.parse((await file.getData("./data/chanpin.json")) || '[]');

    response.json({
        msg: "查询成功",
        data,
        code: 200
    })

})

// http://127.0.0.1:8080/api/prodList/u0000000027876
server.get("/api/prodList/:id", async(request, response) => {


    let id = request.params.id

    var dataList = JSON.parse((await file.getData("./data/chanpin.json")) || '[]');
    let data = dataList.find(item => item.pId == id);

    response.json({
        msg: "查询成功",
        data,
        code: 200
    })

})

// 加入购物车
// get --> query
// post --> body
//  /id-->params.id
server.post("/api/addCart", async(request, response) => {
    let { uId, pId, pName, pPirce, pNumer, pImg } = request.body;
    // console.log(pId);

    //1.去数据库中查询一下,是否购买过
    let sql = "SELECT * FROM `carts` WHERE `uId`=? AND`pId`=? AND `cStatus`=1;";
    let parms = [uId, pId];
    // console.log(parms);
    let isAddCart = (await db.exec(sql, parms)).length >= 1; // 为true 已购买
    // console.log(isAddCart); // false
    if (isAddCart) {
        //修改数量和金额
        let sql_Update = "UPDATE `carts` SET `cNum`=cNum+? ,`cTotal`=cNum*`cPrice` WHERE `uId`=? AND`pId`=? AND `cStatus`=1;";
        let params_Update = [pNumer, uId, pId];

        let isUpdate = (await db.exec(sql_Update, params_Update)).affectedRows >= 1;
        response.json({
            msg: isUpdate ? "加入购物车成功!u" : "加入购物车失败!u",
        })

    } else {
        //插入一条新的购买记录
        let sql_insert = "INSERT INTO `carts` (`uId`,`pId`,`cName`,`cImg`,`cNum`,`cPrice`,`cTotal`)VALUES(?,?,?,?,?,?,?);"
        console.log(typeof(pNumer));
        let params_insert = [uId, pId, pName, pImg, pNumer, pPirce, pNumer * pPirce];
        let isInsert = (await db.exec(sql_insert, params_insert)).affectedRows >= 1;
        response.json({
            msg: isInsert ? "加入购物车成功!i" : "加入购物车失败!i",
        });
    }
})

// 查询接口
server.get("/api/getCarts/:uId", async(request, response) => {

    let sql = " SELECT * FROM `carts` WHERE cStatus=1 AND `uId`=?";
    let parmas = [request.params.uId];
    let result = await db.exec(sql, parmas);
    response.json({
        msg: "查询成功",
        data: result
    })
})

//修改购物车购买数量
server.post("/api/modify", async(request, response) => {
    let sql = 'UPDATE `carts` SET `cNum`=? ,`cTotal`=`cPrice`*`cNum` WHERE `cId`=?;';
    let params = [
            request.body.cNum,
            request.body.cId
        ]
        // console.log(params);
    let result = await db.exec(sql, params); //修改,删除,加入 返回 affectedRows
    console.log(result);
    let isModify = (result && result.affectedRows >= 1)
        // response.json({
        //     // msg: isModify ? "修改成功" : "修改失败"
        // })

})

//删除接口
server.post("/api/delete", async(request, response) => {
    let sql = 'UPDATE `carts` SET `cStatus`=0 WHERE `cId`=?;';
    let params = [
        request.body.cId
    ]
    let result = await db.exec(sql, params); //修改,删除,加入 返回 affectedRows
    let isModify = (result && result.affectedRows >= 1)
    response.json({
        msg: isModify ? "删除成功" : "删除失败",
        code: isModify ? 200 : -200
    })

})


//设置端口
server.listen(8080, () => {
    console.log("服务启动完毕!");
})